<template>
	<image v-if="adCon && adCon.material_url && isBanner" :src="adCon.material_url" :class="[ad_class]" :style="[ad_style]"
		@click="clickYiZunAd" mode="widthFix"></image>
	<view v-else class="cu-modal" :class="{ show: modalValue }">
		<view class="cu-dialog" @click="clickYiZunAd">
			<view v-if="curAdOptions.auto" class="text-modal">
				正在为您推荐更多优选活动...</view>
			<template v-else-if="adCon && adCon.material_url">
				<image :src="adCon.material_url" mode="widthFix"></image>
				<span
					style="position:absolute;top:0px;right:0px;color:#fff;font-size:12px;background:rgba(0,0,0,0.3);line-height:16px;padding:1px 2px;opacity:0.6;">广告</span>
			</template>
		</view>
	</view>
</template>

<script>
function getRequest(url) {
	if (url) {
		let theRequest = new Object()
		if (url.indexOf('?') != -1) {
			let str = url.split('?')[1]
			let strs = str.split('&')
			for (let i = 0; i < strs.length; i++) {
				theRequest[strs[i].split('=')[0]] = decodeURI(strs[i].split('=')[1])
			}
		}
		return theRequest
	} else {
		let curPage = getCurrentPages();
		let params = curPage[curPage.length - 1].options;
		return params;
	}
}
function getUrl(url, data) {
	return url += (url.indexOf('?') < 0 ? '?' : '') + getParam(data)
}
function getParam(data) {
  let url = '';
  for (var k in data) {
    let value = data[k] !== undefined ? data[k] : '';
    url += `&${k}=${encodeURIComponent(value)}`
  }
  return url ? url.substring(1) : ''
}
export default {
	name: "YiZunAd",
	props: {
		cm_key: {
			type: Number,
			default() {
				return 0
			}
		},
		cm_secret: {
			type: String,
			default() {
				return ""
			}
		},
		ad_class: {
			type: String,
			default() {
				return ""
			}
		},
		ad_style: {
			type: Object,
			default() {
				return {

				}
			}
		}
	},
	data() {
		return {
			uuid: null,
			adCon: null,
			isBanner: false,
			modalValue: false,
			request_url: '',
			curAdOptions: {},
		}
	},
	created() {
		this.uuid = uni.getStorageSync("yiZun_uuid");
		if (!this.uuid) {
			this.uuid = this.createUUID();
			uni.setStorageSync('yiZun_uuid', this.uuid)
		}
	},
	methods: {
		renderYiZunAd(options) {
			try {
				const pages = getCurrentPages()
				let startPath = pages[pages.length - 1].$page.fullPath;
				let rawQuery = getRequest(startPath);
				delete rawQuery.ad_params
				let appletPath = getUrl(startPath.split("?")[0], rawQuery);
				this.request_url = encodeURIComponent(appletPath.length > 800 ? "too_long" : appletPath);
			} catch (error) {
				this.request_url = encodeURIComponent("pages/index/index")
			}

			if (!options.clickFb) {
				uni.showToast({
					title: "请先定义点击回调函数clickFb",
					icon: 'none'
				})
				return;
			} else {
				this.clickFb = options.clickFb;
				delete options.clickFb;
			}
			let { displayType, ad_position_id, media_id, goods_name } = options;
			if (!ad_position_id || !media_id || !goods_name) {
				uni.showToast({
					title: "必填参数缺失",
					icon: 'none'
				})
				return;
			}
			this.curAdOptions = options;
			let params = {
				...options,
				"key": this.cm_key,
				"secret": this.cm_secret,
				"uuid": this.uuid,
				"request_url": this.request_url,
				"message": options.msg,
				"retStatus": "1",
				"clientType": "miniProgram"
			}
			this.send({
				url: 'https://dspcoll.adsl.cn/dsp-collector/ssp/getAdAndShow',
				data: params,
			}).then(res => {
				// 智能推荐需要校验必填信息  recommend_type 推荐类型 1:智能推荐 2:人工推荐
				if (
					!this.verifyOptions(options, res.data.scene) &&
					res.data.recommend_type === "1"
				) {
					uni.showToast({
						title: "必填参数缺失",
						icon: 'none'
					})
					return;
				}
				if (res.code === 0 && res.success) {
					this.adCon = res.data;
				}
				//  result.position 广告位置  '3': banner, '4': 弹框, '5': 悬浮
				if (displayType === "modal" || res.data.position === "4") {
					if (res.data.position === "4") {
						options.auto = true;
					}
					this.modalValue = true
				} else { this.isBanner = true }
				if (options.auto === true) {
					setTimeout(() => { this.clickYiZunAd() }, 1000)
				}
			})
		},
		/**
 * 校验必填信息
 * @param {object} options 传入的信息
 * @param {string} scene 广告场景（1:办理失败 2:办理成功 3:退出页面）
 * @returns {boolean}
 */
		verifyOptions(options, scene) {
			const { goods_name, phone, msg } = options;

			if (!scene) return false;

			const isPhoneValid = Boolean(phone) && /^1[3456789]{1}\d{9}$/.test(phone);

			switch (scene) {
				case "3":
					return Boolean(goods_name);
				case "2":
					return Boolean(goods_name) && isPhoneValid;
				case "1":
					return Boolean(goods_name) && Boolean(msg) && isPhoneValid;
				default:
					return false;
			}
		},
		clickYiZunAd() {
			if (!this.adCon) {
				return;
			}
			let params = {
				"key": this.cm_key,
				"secret": this.cm_secret,
				"uuid": this.uuid,
				"request_url": this.request_url,
				"web_url": this.adCon.web_url,
				"material_url": this.adCon.material_url,
				...this.curAdOptions,
				"message": this.curAdOptions.msg
			}
			this.send({
				url: 'https://dspcoll.adsl.cn/dsp-collector/ssp/getClick',
				data: params,
			}).then(res => {
				if (res.code === 0 && res.success) {
					this.clickFb({
						...{
							ad_url: this.adCon.web_url + "&ruleUniqueKey=" +
								this.adCon.rule_unique_key +
								"&retweetTrace=" +
								this.adCon.retweet_trace + '&yi_pre_url=' + this.request_url
						}
					});
				}
			})
			setTimeout(() => { this.modalValue = false }, 2000)
		},
		send(options) {
			if (typeof options !== 'object') {
				return
			}
			options = {
				...{
					url: '',
					method: 'POST',
					'content-type': 'application/json;charset-UTF-8',
					data: {},
					header: {},
				},
				...options,
			}
			if (options.data) delete options.data.ContentType
			options.method = options.method.toUpperCase()
			//发送请求
			return new Promise((resolve, reject) => {
				uni.request({
					url: options.url,
					method: options.method,
					timeout: 1000000,
					data: {
						...options.data,
					},
					header: {
						'content-type': options['content-type'],
						...options.header,
					},
					success: (res) => {
						resolve(res.data)
					},
					fail: (err) => {
						reject(err)
					},
					complete: (data) => { },
				})
			})
		},
		createUUID() {
			var d = new Date().getTime();
			var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
				var r = (d + Math.random() * 16) % 16 | 0
				d = Math.floor(d / 16)
				return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
			})
			return uuid
		}
	}
}
</script>
<style scoped>
.text-modal {
	width: 500rpx;
	min-height: 300rpx;
	padding: 30rpx;
	border-radius: 20rpx;
	color: #fff;
	font-size: 24rpx;
	background: rgba(0, 0, 0, 1);
	display: flex;
	align-items: center;
	justify-content: center;
}

.cu-modal {
	position: fixed;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
	z-index: 99;
	opacity: 0;
	outline: 0;
	text-align: center;
	-ms-transform: scale(1.185);
	transform: scale(1.185);
	backface-visibility: hidden;
	perspective: 2000rpx;
	background: rgba(0, 0, 0, 0.6);
	transition: all 0.3s ease-in-out 0s;
	pointer-events: none;
}

.cu-modal.show {
	opacity: 1;
	transition-duration: 0.3s;
	transform: scale(1);
	overflow-x: hidden;
	overflow-y: auto;
	pointer-events: auto;
	-webkit-overflow-scrolling: touch;
}

.cu-modal::before {
	content: '\200B';
	display: inline-block;
	height: 100%;
	vertical-align: middle;
}

.cu-modal.top-modal::before {
	vertical-align: top;
}

.cu-modal.top-modal .cu-dialog {
	width: 100%;
	border-radius: 0;
}

.cu-modal.top-modal {
	margin-top: -1000rpx;
}

.cu-modal.top-modal.show {
	margin-top: 0;
}

.cu-modal .cu-dialog {
	position: relative;
	display: inline-block;
	vertical-align: middle;
	margin-left: auto;
	margin-right: auto;
	max-width: 100%;
	overflow: hidden;
}
</style>
